import Vue from 'vue'
import Vuex from 'vuex'
import {Store, Getter, Mutation, Action} from 'decorators/vuex'
import Platform from '@/supports/platform'
import {Storage, StorageKeys} from '@/libraries/local'
import axios from 'libraries/axios'

Vue.use(Vuex)

@Store
class RootStore {
  token = sessionStorage.getItem('token') || window.token || ''
  user = {}
  logined = false
  uid = ''
  storeURL = ''
  modifyPassword = ''
  allDesigners = []

  @Getter
  token(state) {
    return state.token
  }

  @Getter
  allDesigners(state) {
    return state.allDesigners
  }

  @Getter
  modifyPassword(state) {
    return state.modifyPassword
  }

  @Getter
  uid(state) {
    return state.user.uid
  }

  @Getter
  user(state) {
    return state.user
  }

  @Getter
  logined(state) {
    return state.logined
  }

  @Mutation
  setModifyPw (state, val) {
    state.modifyPassword = val
  }

  @Mutation
  login(state, user) {
    state.logined = true
    state.token = user.accessToken
    Platform.login(user.accessToken)
  }

  @Mutation
  setUser(state, user) {
    state.user['faceIcon'] = user.faceIcon
    state.user['nickName'] = user.nickName ? user.nickName : ''
    state.user['phone'] = user.phone
    state.user['shopId'] = user.shop.shopId
    state.user['uid'] = user.uid
    state.user['uname'] = user.uname

    state.user['shopHeadPic'] = user.shop.cover
    state.user['shopName'] = user.shop.name
    state.user['shopDec'] = user.shop.description
    state.user['shopWechat'] = user.shop.wechat
    state.user['shopQr'] = user.shop.qr
    Platform.saveValueForKey({'userInfo': state.user})
    sessionStorage.setItem('user', JSON.stringify(state.user))
  }

  @Mutation
  upDateUser(state, user) {
    state.user = user
  }

  @Mutation
  setUid(state, uid) {
    Platform.setUid(uid)
    state.uid = uid
  }

  @Mutation
  logout(state) {
    state.logined = false
    state.token = ''
    state.user = {}
    sessionStorage.setItem('user', '')
    Platform.saveValueForKey({'userInfo': ''})
    Platform.logout()
  }

  @Mutation
  setAllDesigner(state, designers) {
    state.allDesigners = designers
  }

  @Action
  async getAllDesigners ({state, commit}) {
    try {
      let designers = Storage.readStorage(StorageKeys.Designers)

      if (designers instanceof Array && designers && designers.length > 0) {
        commit('setAllDesigner', designers)

        return
      }
      const response = await axios.post('/platform/v1/designers', {})
      if (response.status === 0) {
        let designers = response.data.designers

        commit('setAllDesigner', designers)

        // console.log(state.allDesigners)
      }
      // 写本地缓存
      if (state.allDesigners.length > 0) {
        Storage.writeStorage(StorageKeys.Designers, state.designers, 60)
      }
    } catch (e) {
      console.log(e)
    }
  }
}

export default new Vuex.Store(RootStore)
